<template>
  <scroll-view
    class="tab-bar"
    scroll-x
    show-scrollbar="false"
    scroll-with-animation
    :scroll-left="scrollLeft"
    @scroll="handleScroll"
  >
    <view
      v-for="(tab, index) in tabs"
      :key="tab.id"
      :class="['tab', { active: activeTab === getTabDisplayName(tab) }]"
      @tap="handleTabClick(tab, index)"
      :id="`tab-${index}`"
    >
      {{ getTabDisplayName(tab) }}
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, defineProps, nextTick, getCurrentInstance, defineEmits, watchEffect } from 'vue';

const props = defineProps({
  tabs: {
    type: Array,
    default: () => []
  },
  displayField: {
    type: String,
    default: '' 
  }
});

const emits = defineEmits(['custom-click']);
const activeTab = ref('');
const scrollLeft = ref(0);
const currentScrollLeft = ref(0);
const instance = getCurrentInstance();

// 监听props.tabs的变化，确保在tabs更新时activeTab能正确处理
watchEffect(() => {
  if (props.tabs.length > 0 &&!activeTab.value) {
    activeTab.value = getTabDisplayName(props.tabs[0]);
  }
});

const getTabDisplayName = (tab) => {
  return tab[props.displayField];
};

const handleTabClick = (tab, index) => {
  activeTab.value = getTabDisplayName(tab);
  emits('custom-click', tab);
  nextTick(() => {
    uni.createSelectorQuery().in(instance)
     .select(`#tab-${index}`)
     .boundingClientRect((tabRect) => {
        if (!tabRect) {
          console.error(`未找到 #tab-${index} 元素`);
          return;
        }
        uni.createSelectorQuery().in(instance)
         .select('.tab-bar')
         .boundingClientRect((tabBarRect) => {
            if (!tabBarRect) {
              console.error('未找到 .tab-bar 元素');
              return;
            }
            const offset = tabBarRect.left + 80;
            const scrollDistance = tabRect.left - offset;
            scrollLeft.value = currentScrollLeft.value + scrollDistance;
          })
         .exec();
      })
     .exec();
  });
};

const handleScroll = (e) => {
  currentScrollLeft.value = e.detail.scrollLeft;
};
</script>

<style scoped>
.tab-bar {
  white-space: nowrap;
  scrollbar-width: none;
  padding: 10px 0;
  background-color: #fff;
  overflow: hidden;
  -webkit-overflow-scrolling: touch;
}

.tab {
  display: inline-block;
  padding: 8px 16px;
  margin-right: 10px;
  cursor: pointer;
  border-radius: 20px;
  background-color: #f5f5f5;
  color: #333;
}

.tab.active {
  background-color: #07c160;
}
</style>